package com.lin.mr.maizilaundry.fragmentcloth;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.smartimage.SmartImageView;
import com.google.gson.Gson;
import com.lin.mr.maizilaundry.R;
import com.lin.mr.maizilaundry.entity.Laundry;
import com.lin.mr.maizilaundry.myadapter.VolleyAdapter;
import com.lin.mr.maizilaundry.myapplication.MyApplication;
import com.lin.mr.maizilaundry.utils.CountEvent;
import com.lin.mr.maizilaundry.utils.TimeUtils;
import com.lin.mr.maizilaundry.utils.VolleyUtils;
import com.lin.mr.maizilaundry.utils.WashInfoJean;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by lenovog on 2016/8/7.
 */
public class FragmentVolley extends Fragment implements View.OnClickListener{
    private GridView gridView;
    private ProgressBar pb;
    private PopupWindow popupWindow;
    private SmartImageView iv_picture;
    private TextView tv_name;
    private TextView tv_price;
    private TextView tv_sum;
    private ImageButton btn_minus;
    private ImageButton btn_plus;
    private Button btn_sure;
    private Laundry laundry;
    int currentPosition;//选中的的GridView的项的下标号
    int previousSum;
    int currentSum;
    private String currentTime;//用户下单时的时间

    private List<WashInfoJean.WashInfoBean> washList;

    private String URL = "http://cloud.bmob.cn/d9f6840be6bb07cf/wash_test?clive=wash";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_volley, null);
        gridView = (GridView) view.findViewById(R.id.gridView_volley);
//        gridView.setVisibility(View.INVISIBLE);//在GridView加载数据之前将其设为不可见
        pb = (ProgressBar) view.findViewById(R.id.progressBar);
        return view;
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if (isVisibleToUser) {
            VolleyUtils.requestByGet(URL, "FragmentVolley", new VolleyUtils.CallBack() {
                @Override
                public void returnData(Object result) {
                    if (result != null) {
                        Gson gson = new Gson();
                        WashInfoJean washJean = gson.fromJson((String) result, WashInfoJean.class);
                        washList = new ArrayList<WashInfoJean.WashInfoBean>();
                        washList = washJean.getWashInfo();
                        gridView.setAdapter(new VolleyAdapter(getActivity(), washList));
                        initPopupWindow();
                        //延时2s显示GridView
                        new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                try {
                                    Thread.sleep(2000);
                                    handler.sendEmptyMessage(0);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                //使用runOnUiThread可以在主线程更新UI
                                //由于主线程在Activity中，所以要用getActivity()调用
//                                if (getActivity()!=null){
//                                    getActivity().runOnUiThread(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            pb.setVisibility(View.INVISIBLE);
//                                            gridView.setVisibility(View.VISIBLE);
//                                        }
//                                    });
//                                }

                            }
                        }.start();

                        //gridView的点击事件
                        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                currentPosition = position;
                                showPopupWindow(position);
                                if (popupWindow != null && popupWindow.isShowing()) {
                                    popupWindow.dismiss();
                                } else {
                                    tv_sum.setText("1");//将PopupWindow中的衣服件数初始化为1
                                    popupWindow.showAtLocation(gridView, Gravity.BOTTOM, 0, 0);
                                }
                            }
                        });
                    } else {
                        Toast.makeText(getActivity(), "请检查网络", Toast.LENGTH_SHORT).show();
                    }
                }
            });

        }

    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            pb.setVisibility(View.INVISIBLE);
            gridView.setVisibility(View.VISIBLE);
        }
    };

    private void showPopupWindow(int position) {
        //这里加载图片采用的是SmartImageView
        iv_picture.setImageUrl(washList.get(position).getWashHead(), R.mipmap.ic_launcher, R.mipmap.error);
        tv_name.setText(washList.get(position).getWashName());
        tv_price.setText(washList.get(position).getAmount());
    }

    private void initPopupWindow() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.popupwindow_item, null);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        //设置PopupWindow的属性
        ColorDrawable dw = new ColorDrawable(getResources().getColor(R.color.color_second_text));//设置背景色
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.getBackground().setAlpha(50);//设置透明度
        popupWindow.setOutsideTouchable(true);//设置可以点击
        popupWindow.setFocusable(true);//使popupwindow获得焦点
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        //初始化控件
        iv_picture = (SmartImageView) view.findViewById(R.id.pop_bag_image);
        tv_name = (TextView) view.findViewById(R.id.pop_bag_text);
        tv_price = (TextView) view.findViewById(R.id.pop_bag_price);
        tv_sum = (TextView) view.findViewById(R.id.pop_bag_sum);
        btn_minus = (ImageButton) view.findViewById(R.id.pop_bag_minus);
        btn_plus = (ImageButton) view.findViewById(R.id.pop_bag_plus);
        btn_sure = (Button) view.findViewById(R.id.btn_pop_sure);

        btn_minus.setOnClickListener(this);
        btn_plus.setOnClickListener(this);
        btn_sure.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.pop_bag_minus:
                getPreviousSum();
                if (previousSum > 1){
                    currentSum = previousSum -1;
                    tv_sum.setText(currentSum+"");
                }
                break;
            case R.id.pop_bag_plus:
                getPreviousSum();
                currentSum = previousSum +1;
                tv_sum.setText(currentSum+"");
                break;
            case R.id.btn_pop_sure:
                if (popupWindow != null && popupWindow.isShowing()){
                    Boolean isRepeat = isRepeatedData();
                    String name = (String) tv_name.getText();
                    if (isRepeat){ //判断是否之前是否有添加进洗衣篮的衣服
                        for (int i=0;i<MyApplication.laundries.size();i++){
                            laundry = MyApplication.laundries.get(currentPosition);
                            //判断洗衣篮中的衣服是否跟用户当前选择的衣服相同
                            if (name.equals(laundry.getPictureName())){
                                //获取洗衣篮中的件数
                                String string1 = laundry.getAmount();
                                int amount1 = Integer.parseInt(string1);
                                //获取用户当前添加的件数
                                String string2 = (String) tv_sum.getText();
                                int amount2 = Integer.parseInt(string2);
                                //将之前添加的件数和当前添加的件数相加
                                laundry.setAmount(amount1 + amount2 +"");
                                break;
                            }
                        }
                    }else {
                        Laundry laundry = new Laundry();
                        laundry.setPicture(washList.get(currentPosition).getWashHead());//图片
                        laundry.setValue((String) tv_price.getText());//价格
                        laundry.setAmount((String) tv_sum.getText());//数量
                        laundry.setPictureName((String) tv_name.getText());
                        //获取下单时的时间
                        currentTime = TimeUtils.getTime(System.currentTimeMillis());
                        laundry.setTime(currentTime);
                        MyApplication.laundries.add(laundry);
                    }
                    Toast.makeText(getActivity(), "已加入到洗衣篮(∩_∩)", Toast.LENGTH_SHORT).show();
                    popupWindow.dismiss();
                    //悬浮图标
                    EventBus.getDefault().post(new CountEvent(4));
                }
                break;
        }

    }

    //获取PopupWindow中的件数
    public void getPreviousSum(){
        String text = tv_sum.getText().toString();
        previousSum = Integer.parseInt(text);
    }

    /**
     * 判断是否有重复数据
     * @return
     */
    private Boolean isRepeatedData(){
        String tv_nameText = (String) tv_sum.getText();
        for (int i = 0; i< MyApplication.laundries.size(); i++){
            laundry = MyApplication.laundries.get(i);
            if (tv_nameText.equals(laundry.getPictureName())){
                return true;
            }
        }
        return false;
    }

}
